package com.moyun.syssecurity.handler;

import com.alibaba.fastjson.JSON;
import com.moyun.common.enums.CodeEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * <h3>moyun-base</h3>
 * <p>自定义权限异常处理类</p>
 *
 * @author : ybx
 * @date : 2021-08-30 15:53:00
 **/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json; charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter out = response.getWriter();
        // 输出失败的原因  401 认证失败
//                    out.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");
//        out.write("{\"code\":\"401\",\"msg\":\"" + errorMsg + "\"}");
        // 这里我们不使用字符串拼接的方式返回json格式的数据  可以自定义发送内容 登录失败后信息会被封装到AutehnticationException类中，返回信息即可
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", CodeEnum.FAIL.getCode());
        map.put("msg", accessDeniedException.getMessage());
        out.write(JSON.toJSONString(map));
        out.flush();
        out.close();

    }
}
